/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName ConfigLoader.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model
{
	
	import com.gesturesoft.imultimax.AppConst;
	import com.gesturesoft.imultimax.events.CustomProgressEvent;
	import com.gesturesoft.imultimax.model.completor.Completor;
	import com.gesturesoft.imultimax.model.interfaces.IConfigLoader;
	import com.gesturesoft.imultimax.model.loader.events.LoadFaultEvent;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.external.ExtensionContext;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	public class ConfigLoader extends Completor  implements IConfigLoader
	{
		
		private var url:String;
		private var configService:HTTPService;
		private var _data:String;
		private var netConnected:Boolean = true;
		
		public function ConfigLoader(_url:String)
		{
			
			url = _url;
			
		}
		
		/*
		Load config xml from server
		*/
		
		public function loadConfig():void
		{
			
			var urlloader:URLLoader = new URLLoader();
			configureListerners(urlloader);
			urlloader.load(new URLRequest(url));
			
		}
		
		private function configureListerners(urlloader:URLLoader):void
		{
			
			urlloader.addEventListener(Event.COMPLETE, onComplete);
			urlloader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			urlloader.addEventListener(IOErrorEvent.IO_ERROR, onLoadFailed);
			urlloader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			
		}
		
		private function onProgress(e:ProgressEvent):void
		{
			
			dispatchEvent(new CustomProgressEvent(CustomProgressEvent.LOAD_PROGRESS,e.bytesLoaded,e.bytesTotal));
			
		}
		
		private function onComplete(event : Event):void
		{
			
			data = event.target.data;
			super.complete(this);
			
		}
		
		private function onLoadFailed(event : IOErrorEvent):void
		{
			
			if(netConnected)
			{
				
				dispatchEvent(new LoadFaultEvent(LoadFaultEvent.LOAD_FAILED, "Config file load failed"));
				trace("config xml load failed");
				
			}
			
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void
		{
			
			if(event.status == 0)
			{
				
				netConnected = false;
				dispatchEvent(new LoadFaultEvent(LoadFaultEvent.LOAD_FAILED, AppConst.NET_CONNECTION_FAILED));
				
			}
			
		}
		
		public function get data():String
		{
			
			return _data;
			
		}
		
		public function set data(data:String):void
		{
			
			_data = data;
			
		}
			
	}
	
}